import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DynamicProxy {

    public static void main(String[] args) {
       /** 动态代理代码测试 Aop切面就是基于动态代理实现的 */
        ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler();
        proxyInvocationHandler.setTarget(new TargetClass());
        TargetInterface targetClass = (TargetInterface)proxyInvocationHandler.getProxy();
        targetClass.sayHello();
    }

}

//-------* jdk动态代理 *----------------------

interface TargetInterface {
    public void sayHello();
}

/**
 * 被代理类/目标类
 */
class TargetClass implements TargetInterface {
    public void sayHello() {
        System.out.println("Hello World...");
    }
}

/**
 * 动态代理类
 */
class ProxyInvocationHandler implements InvocationHandler {
    private Object target;

    public void setTarget(Object target) {
        this.target = target;
    }

    public Object getProxy() {
        return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before hello ... ");
        Object result = method.invoke(target, args);
        System.out.println("after hello... ");
        return result;
    }

    public void log(String s) {
        System.out.println("[debug]:" + s);
    }
}


